import {
  ArticleQueryType,
  collectByIdAPI,
  followUserByIdAPI,
  getArticleDetailsByIdAPI,
  getArticleListByIdAPI,
  likeByIdAPI,
  unCollectByIdAPI,
  unFollowUserByIdAPI,
  unLikeByIdAPI,
} from '@/api/article';
import { AppDispatch } from '../reducer';
import { ArticleActionType } from '../reducer/article';

/**获取文章列表Action */
export function getArticleListByIdAction({
  channel_id,
  timestamp = Date.now(),
}: ArticleQueryType) {
  return async (dispatch: AppDispatch) => {
    const res = await getArticleListByIdAPI({ channel_id, timestamp });
    console.log(res);
    // res.data.results = res.data.results.map((item:any) => ({...item,aut_name:'test'}))
    dispatch({
      type: 'article/saveList',
      // payload: { ...res.data, channel_id },
      payload: { ...res.data, channel_id },
    });
  };
}

/**无限滚动加载更多Action */
export function updateArticleAction({
  channel_id,
  timestamp = Date.now(),
}: ArticleQueryType) {
  return async (dispatch: AppDispatch) => {
    const res = await getArticleListByIdAPI({ channel_id, timestamp });
    // console.log(res);
    // res.data.results = res.data.results.map((item:any) => ({...item,aut_name:'test'}))
    dispatch({
      type: 'article/updateList',
      payload: { ...res.data, channel_id },
    });
  };
}

/**获取文章详情Action */
export function getArticleDetailsByIdAction(id: string) {
  return async (dispatch: AppDispatch) => {
    const res = await getArticleDetailsByIdAPI(id);
    // console.log(res);
    dispatch({
      type: 'article/saveDetails',
      payload: res.data,
    });
  };
}

/**清除文章详情Action */
export function delArticleDetailsAction(): ArticleActionType {
  return { type: 'article/delDetails' };
}

/** 更新文章评论数Action */
export function updateDetailsCommentsAction(
  comm_count: number
): ArticleActionType {
  return { type: 'article/updateDetailsComm_count', payload: comm_count };
}

/** 关注用户Action */
export function followUserByIdAction(target: string) {
  return async (dispacth: AppDispatch) => {
    await followUserByIdAPI({ target });
    // console.log(res);
  };
}

/** 取消关注用户Action */
export function unFollowUserByIdAction(target: string) {
  return async (dispacth: AppDispatch) => {
    await unFollowUserByIdAPI(target);
    // console.log(res);
  };
}

/** 对文章点赞/取消点赞Action */
export function likeByIdAction(target: string, bool: boolean) {
  return async (dispacth: AppDispatch) => {
    if (bool) {
      await likeByIdAPI({ target });
    } else {
      await unLikeByIdAPI(target);
    }
  };
}

/** 对文章收藏/取消收藏Action */
export function collectByIdAction(target: string, is_Collect: boolean) {
  return async (dispacth: AppDispatch) => {
    if (!is_Collect) {
      await collectByIdAPI({ target });
    } else {
      await unCollectByIdAPI(target);
    }
  };
}
